#!/bin/bash
#########################################
# A script to launch the SXE
#
# try to find host's IP address -- this
# works even if behind a firewall/router
#
ip=`curl -s --retry 3 --retry-delay 10 http://whatismyip.org/`

# should that fail, select IP with the lowest metric
# credit goes to an anonymous forum post
if [ "$?" -ne "0" ]; then
	echo "whatismyip.org FAILED.  Trying route..."
  ip=`route print | egrep "^ +0.0.0.0 +0.0.0.0 +" | gawk 'BEGIN {
	metric=255; ip="0.0.0.0"; } { if ( $5 < metric ) { ip=$4; metric=$5; }
	} END { printf("%s\n",ip); }'`
	
	if [ "$?" -ne "0" ]; then
		echo "could not find IP address of local host" || exit 1
	fi
fi

echo Current ip is $ip 1>&2

# now, endlessly run the SXE (restarting as needed)
COUNTER=0
# while [ true ]; do
	TMPFILE=`mktemp logs/sxe.XXXXXXXXXX` || exit 1
	mdate=`date +Date:\[%F\]Time:%H\.%M\.\%S`
	echo $mdate >> $TMPFILE
	echo "Running [$COUNTER]: java -cp . sxe.Server http://$ip:8080 http://resourcemonitor.bu.edu:8079 &>> $TMPFILE"
	java -cp .:lib/jmf.jar:lib/jcommon-1.0.9.jar:lib/jfreechart-1.0.5.jar:lib/mysql-connector-java-5.0.3-bin.jar:lib/jgraphlayout.jar:lib/jgrapht-jdk1.5.jar  sxe.Server --localuri http://$ip:8080 --ssduri NONE >> $TMPFILE
	pkill -9 java
    let COUNTER=COUNTER+1 
# done
         
